<?php
class Userinfo{
	public static $SCOPE_BASW = 'snsapi_base';
	public static $SCOPE_USERINFO = 'snsapi_userinfo';
	private $appid = '';
	private $secret = '';
	private $party = null;
	private $current_account = null;

	function __construct($current_account){
		$this->appid = $current_account['key'];
		$this->secret = $current_account['secret'];
		$this->current_account = $current_account;

		/*if($current_account['type'] == 4){
			load()->classs('thridparty.account');
			$this->party = new ThirdPartyAccount();
		}
		if($current_account['type'] == 3){
			load()->classs('weixin.platform');
			$this->party = new WeiXinPlatform($current_account);
		}*/
	}

	public function user_code($redirect_uri,$scope,$state){
		$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->appid."&redirect_uri=".urlencode($redirect_uri)."&response_type=code&scope=".$scope."&state=".$state."#wechat_redirect";
		
		header("location: $url");
	}
	public function get_access_token($code){
		load()->func('communication');
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->appid."&secret=".$this->secret."&code=".$code."&grant_type=authorization_code";
		$content = ihttp_get($url);
		$token = json_decode($content['content'],true);
		if(empty($token) || !is_array($token) || empty($token['access_token']) || empty($token['openid'])){
			echo '<h1>获取微信公众号授权' . $code . '失败[无法取得token以及openid], 请稍后重试！ 公众平台返回原始数据为: <br />' . $content['meta'] . '<h1>';
            exit();
		}
		return $token;
	}
	public function get_user_info($openid,$access_token){
		$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
		$content = ihttp_get($url);
		$userinfo = json_decode($content['content'],true);
		return $userinfo;
	}
	public function saveuserinfo($userinfo,$cookiekey){
		if(!empty($userinfo) && !empty($cookiekey)){
			$cookie = [];

    		$cookie['uid'] = $userinfo['uid'];
    		$cookie['nickname'] = $userinfo['nickname'];
    		$cookie['headimgurl'] = $userinfo['headimgurl'];
    		$str = base64_encode(json_encode($cookie));

    		isetcookie($cookiekey,$str,4*3600);
			return $str;
		}
	}
}
?>